﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LAP
{
    class File
    {
        private string fileNmae;
        private long fileSize = 0;

        public File(String path)
        {

            // 1.保存文件名
            fileNmae = path;

            // 3.获取文件大小
            try{
                if(new FileInfo(path).Exists)
                    fileSize = new FileInfo(path).Length;
            }
            catch (EndOfStreamException){
                fileSize = 0;
            }
         }

        // 返回文件大小
        public long GetFileSize() { return fileSize; }


        // 写入数据到文件
        public int Write(byte[] buffer, int index, int count)
        {
            FileStream fileStream = new FileStream(fileNmae, FileMode.Open);
            System.IO.BinaryWriter FileBinary = new BinaryWriter(fileStream);
            try
            {
                FileBinary.Write(buffer, index, count);
            }
            catch (EndOfStreamException)
            {
                FileBinary.Close();
                Console.WriteLine(fileNmae + " Write Err!");
                return 0;
            }
            return count;
        }



        public int Read(byte[] buffer, int offset, int count)
        {
            FileStream fileStream = new FileStream(fileNmae, FileMode.Open);
            BinaryReader FileReadBinary = new BinaryReader(fileStream);
            int len = 0;
            try
            {
                fileStream.Position = offset;
                len = FileReadBinary.Read(buffer, 0, count);
            }
            catch (EndOfStreamException)
            {
                Console.WriteLine(fileNmae + " Read Err!");
                FileReadBinary.Close();
                return 0;
            }

            FileReadBinary.Close();
            return len;
        }
    }
}
